import type { FC } from 'react';
import { useEffect, useRef } from 'react';
import type { IProps } from '@/components/KeepAliveOutlet/type';
import {useMemoizedFn} from "ahooks";

export const Repeater: FC<IProps> = (props) => {
	const { mode, children } = props;
	const resolveRef = useRef<() => void>();

	const resolvePromise = useMemoizedFn((ignoreMode?: boolean) => {
		if ((ignoreMode || mode === 'visible') && typeof resolveRef.current === 'function') {
			resolveRef.current();
			resolveRef.current = void 0;
		}
	});

	useEffect(() => () => resolvePromise(true), []);

	if (mode === 'hidden' && typeof resolveRef.current === 'undefined') {
		throw new Promise<void>((resolve) => {
			resolveRef.current = resolve;
			return;
		});
	}


	resolvePromise();

	return <>{children}</>;
};
